#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@文件   :control_Accident.py
@说明   :
@时间   :2024/04/28 12:39:46
@作者   :TaoHong
@版本   :v1.0
'''



import traci


class Accident:
    def __init__(self):
        """
        初始化
        """

    def accident_vehicle_init(self, step, acc_scene_dict):
        
        self.emerg_id = acc_scene_dict['emerg_id']   #! 事故车辆
        self.emerg_edge = acc_scene_dict['emerg_edge']
        
        self.start_emerg_step = acc_scene_dict['start_emerg_step']
        self.end_emerg_step = acc_scene_dict['end_emerg_step']
        self.brake_len = acc_scene_dict['brake_len']

        if step == self.start_emerg_step: # 大于开始时间
            #! 设置stop
            if self.emerg_id in traci.edge.getLastStepVehicleIDs(self.emerg_edge):
                
                # dis = traci.vehicle.getDistance(self.emerg_id)
                # if dis > 4100: # 尽量不要超过 edge 28之外
                #! 减速
                acc_pos = traci.vehicle.getDistance(self.emerg_id)
                acc_pos = traci.vehicle.getLanePosition(self.emerg_id) # 在

                acc_lane_index  = 1 # 停车的车道
                

                # print(f'事故车的里程 {acc_pos}')
                # print(f'初始化事故车的位置： {acc_pos}')


                traci.vehicle.setStop(vehID = self.emerg_id
                                      , edgeID = self.emerg_edge
                                      , pos = acc_pos + self.brake_len # 设置的位置要在后面一定距离
                                      , laneIndex = acc_lane_index
                                      , duration= self.end_emerg_step-self.start_emerg_step
                                      )
            
        #! duration 结束后，车辆会自己离开
        
        # elif step >= self.start_emerg_step: # 查看停车时刻
        #     sp = traci.vehicle.getSpeed(self.emerg_id) 
        #     if sp > 0:
        #         print(f'时间：{step} 速度：{sp}')
    


    def run_accident(self, sumo_cmd, acc_scene_dict, PORT=7911):
        #! 事故场景的输入
        
        #! 事故逻辑：
        # 1, 设置stop: step == self.start_emerg_step
        # 2，维持stop：step > self.start_emerg_step and step < self.end_emerg_step
        # 3，解除stop：step == self.end_emerg_step
        
        traci.init(PORT, label="main")
        traci.setOrder(1)


        step = 0
        while traci.simulation.getMinExpectedNumber() > 0:
            traci.simulationStep()
            step += 1
            # more traci commands
            
            self.accident_vehicle_init(step, acc_scene_dict)

            if step == 1000:
                break
                    
        traci.close()

